package com.jml.disruptortest001;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.nio.ByteBuffer;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class Main {

    public static void main(String[] args) throws InterruptedException {
        // 创建线程池缓冲池
        Executor executor = Executors.newCachedThreadPool();
        // 创建工程
        LongEventFactory factory = new LongEventFactory();
        // 2的次方的大小，缓冲区的大小，RingBuffer
        int bufferSize = 1024;
        // Construct the Disruptor
        //第一个参数是，工厂类对象创建LongEvent，
        // 第二个参数是缓冲区大小要是2的次方，
        // 第三个参数是线程池，利用线程池进行Disrupter内部数据接收处理调度，
        //第四个参数是ProducerType.SINGLE 或者 ProducerType.MULTI,前者表示生产者只有一个，后者表示生产者有多个。
        //第五个参数是一种策略，是做协调的
        //new YieldingWaitStrategy()是性能最好的策略，适用于低延迟的系统，对性能有保证用这个
        //new BlockingWaitStrategy()是最低效的策略，但是对cpu损耗小，在不同的部署坏境中可以提供很强的一致性性能
        //new SleepingWaitStrategy()是最低效的策略，但是对cpu损耗小，对生产者线程影响比较小，适用于异步日志
        Disruptor<LongEvent> disruptor = new Disruptor<LongEvent>(factory, bufferSize, executor,ProducerType.SINGLE,new YieldingWaitStrategy());
        // 连接消费事件的方法，可以把handler理解为消费者，handler是建立监听的
        disruptor.handleEventsWith(new LongEventHandler());
        // 启动disruptor
        disruptor.start();
        // RingBuffer(是真正放数据的地方
        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();
        LongEventProducer producer = new LongEventProducer(ringBuffer);
        //或者是：jdk包装好的东西
        LongEventProducerWithTranslator producers = new LongEventProducerWithTranslator(ringBuffer);
        ByteBuffer bb = ByteBuffer.allocate(8);
        for (long l = 0; l<100L; l++) {
            bb.putLong(0, l);
            producer.onData(bb);
            Thread.sleep(1000);
        }
    }
}
